<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ss_model extends CI_Model {

	public function get_list(){
		return $this->db->get('tbl_siswa');
	}

	public function get_data($id){
		$this->db->where('ss_id',$id);
		$get = $this->db->get('tbl_siswa');
		if($get->num_rows() > 0){
			$row = $get->row_array();
			$id_user = $row['ss_id_user'];
		}
		$this->db->select('a.ss_id,a.ss_real_name,a.ss_ttl,a.ss_jk,a.ss_email,a.ss_alamat,b.username');
		$this->db->from('tbl_siswa a');
		$this->db->join('users b','a.ss_id_user = b.id_user AND b.level = 4');
		$this->db->where('a.ss_id_user',$id_user);
		return $this->db->get();
	}

	public function do_add($param = false){
		if($param){
			if($param['ss_password']){
				$password = md5($param['ss_password']);
				$this->db->set('password',$password);
				$this->db->set('id_session',$password);
				unset($param['ss_password']);
			}
			$this->db->set('level',4);
			$this->db->set('username',$param['ss_username']);
			$this->db->insert('users');
			
			unset($param['ss_username']);
			$id = $this->db->insert_id();
			
			$this->db->set('ss_id_user',$id);
			$this->db->insert('tbl_siswa',$param);
			return true;
		}
		return false;
	}

	public function do_update($id = false,$param = false){
		if($id){
			$this->db->where('ss_id',$id);
			$get = $this->db->get('tbl_siswa');
			if($get->num_rows() > 0){
				$row = $get->row_array();
				$id_user = $row['ss_id_user'];
			}

			if($param['ss_password']){
				$password = md5($param['ss_password']);
				$this->db->set('ss_password',$password);
				unset($param['ss_password']);
			}else{
				unset($param['ss_password']);
			}
			
			$this->db->set('username',$param['ss_username']);
			$this->db->where('id_user',$id_user);
 			$this->db->update('users');

 			unset($param['ss_username']);

			$this->db->where('ss_id',$id);
			return $this->db->update('tbl_siswa',$param);
		}
		return false;
	}

	public function do_delete($id = false){
		if($id){
			$this->db->where('ss_id',$id);
			$get = $this->db->get('tbl_siswa');
			if($get->num_rows() > 0){
				$row = $get->row_array();
				$this->db->where('id_user',$row['ss_id_user']);	
				$this->db->where('level',4);	
				$this->db->delete('users');
			}
			$this->db->where('ss_id',$id);
			return $this->db->delete('tbl_siswa');
		}return false;
	}
}